<template>
  <div class="device-detail-dialog-page">
    <el-dialog
      :model-value="props.dialogVisible"
      title="绑定用户"
      width="800px"
      :close-on-click-modal="false"
      :before-close="handleClose">
      <el-form ref="searchParamsRef" :model="searchParams" @submit.prevent="search">
        <el-row :gutter="16">
          <el-col :span="8">
            <el-form-item label="用户姓名：" prop="name">
              <el-input v-model="searchParams.name" clearable placeholder="请输入用户姓名" style="width: 100%;"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="手机号码：" prop="phone">
              <el-input v-model="searchParams.phone" clearable placeholder="请输入手机号码" style="width: 100%;"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item>
              <el-button type="primary" @click="search">查询</el-button>
              <el-button @click="reset">重置</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <div class="data-block">
        <el-table ref="multipleTableRef" :data="tableData" :height="400" class="nr-table">
          <el-table-column type="selection" width="30"/>
          <el-table-column label="用户姓名" prop="username"></el-table-column>
          <el-table-column label="手机号码" prop="phoneNum"></el-table-column>
          <el-table-column label="所属项目" prop="projectName"></el-table-column>
        </el-table>
        <el-pagination
          class="nr-page"
          v-model:current-page="searchParams.currentPage"
          v-model:page-size="searchParams.pageSize"
          :page-sizes="[10, 20, 30, 40]"
          background
          layout="total, prev, pager, next, sizes, jumper"
          :total="searchParams.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange">
        </el-pagination>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleClose">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts" name="DeviceDetailDialog">
import { ref, reactive, watch, ComponentInternalInstance, getCurrentInstance, onMounted, nextTick } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import { ElMessage, ElMessageBox, ElTable } from 'element-plus'
import { userListPage } from '@/api/user-manage'
import { bindUserBatch } from '@/api/bind'

const { proxy } = getCurrentInstance() as ComponentInternalInstance

const emit = defineEmits(['submit', 'update:dialogVisible'])
const props = defineProps({
  dialogVisible: {
    type: Boolean,
    default: false
  },
  formData: {
    type: Object,
    default: {}
  }
})

const searchParamsRef = ref<FormInstance>()
const searchParams = reactive({
  name: '',
  phone: '',
  currentPage: 1,
  pageSize: 10,
  total: 0
})
const multipleTableRef = ref<InstanceType<typeof ElTable>>()
const tableData = ref<any>([])

watch(() => props.dialogVisible, async (newVal) => {
  if (newVal) {
    getUserData()
  }
})

// 查询
const search = () => {
  searchParams.currentPage = 1
  getUserData()
}

// 重置
const reset = () => {
  searchParamsRef.value?.resetFields()
}

// 分页跳转
const handleCurrentChange = (val: number) => {
  getUserData()
}
const handleSizeChange = (val: number) => {
  getUserData()
}

// 重置表单
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}

// 关闭弹窗
const handleClose = () => {
  resetForm(searchParamsRef.value)
  searchParams.currentPage = 1
  searchParams.pageSize = 10
  searchParams.total = 0
  tableData.value = []
  proxy?.$emit('update:dialogVisible', false)
}

// 提交表单
const handleSubmit = async () => {
  let arr = <any>[...multipleTableRef.value?.getSelectionRows()]
  if (arr.length === 0) {
    ElMessage.error(`未选择用户！`)
    return false
  }
  let userIds = <any>[]
  arr.map((item: any) => {
    userIds.push(item.id)
  })
  let params = {
    deviceId: props.formData.id,
    userIdList: userIds,
  }
  await bindUserBatch(params).then((res: any) => {
    if (res.code === 0) {
      ElMessage.success(`绑定成功！`)
      emit('submit')
    } else {
      ElMessage.error(`${res.msg}`)
    }
  }).catch(err => {
    console.log(err)
  })
}

// 获取用户表格数据
const getUserData = async () => {
  let params = {
    phoneNum: searchParams.phone,
    username: searchParams.name,
    currentPage: searchParams.currentPage,
    pageSize: searchParams.pageSize
  }
  await userListPage(params).then((res: any) => {
    if (res.code === 0) {
      tableData.value = [...res.list]
      searchParams.total = res.page.totalSize
    } else {
      ElMessage.error(`${res.msg}`)
    }
  }).catch(err => {
    console.log(err)
  })
}
</script>

<style lang="stylus" scoped>
@import '../../style/base.styl'
</style>
